<template>
  <div class="page-container">
    <div class="card-title" v-show="showSearch">
      <el-form size="small" label-width="68px" :model="queryParams" ref="queryForm">
        <el-row :gutter="48">
          <el-col :md="6" :sm="24">
            <el-form-item label="字典类型">
              <el-select v-model="queryParams.dictTypeId" placeholder="请选择字典类型" class="search-item" clearable>
                <el-option v-for="item in dictTypeOptions" :key="item.dictTypeId" :label="item.dictName" :value="item.dictTypeId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="数据标签">
              <el-input v-model="queryParams.dictLabel" class="search-item" placeholder="请输入数据标签" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择字典数据状态" class="search-item" clearable>
                <el-option v-for="dict in dict.type.sys_active_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <!-- 创建时间 -->
            <el-form-item label="创建时间" v-if="advanced">
              <el-date-picker
                v-model="queryParams.dataRange"
                class="search-item"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <div class="search-content">
            <!-- 搜索按钮 -->
            <el-form-item class="search-button">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
              <el-button
                type="text"
                :icon="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                class="advanced-button"
                @click="toggleAdvanced">
                {{ advanced ? '关闭' : '展开' }}
              </el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <div class="card">
      <el-row :gutter="10" class="button-container">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini" plain>
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" plain :disabled="single" @click="handleUpdate">编辑</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" plain :disabled="multiple" @click="handleDelete" :loading="buttonLoading">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-close" size="mini" plain :loading="buttonLoading" @click="close">关闭</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" :columns="columns" @getTableData="getTableData"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" element-loading-text="正在加载表格数据" :data="tableData" @selection-change="handleSelectionChange" border>
        <template slot="empty">
          <el-empty :image-size="200"></el-empty>
        </template>
        <el-table-column type="selection" width="50" align="center" />
        <!-- 字典排序 -->
        <el-table-column prop="sort" label="字典排序" align="center" v-if="columns[0].visible"></el-table-column>
        <!-- 数据标签 -->
        <el-table-column prop="dictLabel" label="数据标签" align="center" v-if="columns[1].visible" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag :type="scope.row.listClass">{{ scope.row.dictLabel }}</el-tag>
          </template>
        </el-table-column>
        <!-- 数据键值 -->
        <el-table-column prop="dictValue" label="数据键值" align="center" v-if="columns[2].visible" show-overflow-tooltip></el-table-column>
        <!-- 状态 -->
        <el-table-column prop="status" label="状态" align="center" v-if="columns[3].visible">
          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.status">正常</el-tag>
            <el-tag type="danger" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <!-- 备注 -->
        <el-table-column prop="remark" label="备注" align="center" v-if="columns[4].visible"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" v-if="columns[5].visible">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <pagination
        :background="false"
        :total="total"
        :page.sync="queryParams.currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableData"
      />
    </div>

    <!-- 字典数据信息对话框 -->
    <el-dialog
      :title="dictDataTitle"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :visible="dictDataVisible"
      :before-close="handleClose">
      <div class="dictData-wrapper" v-loading="dictDataLoading" element-loading-text="正在加载字典数据信息">
        <el-form ref="dictDataForm" :model="formData" :rules="rules" label-width="80px" label-position="right">
          <el-row :gutter="15">
            <!-- 字典类型 -->
            <el-form-item label="字典类型" prop="dictTypeId">
              <el-select v-model="queryParams.dictTypeId" style="width: 100%;" disabled>
                <el-option
                  v-for="item in dictTypeOptions"
                  :key="item.dictTypeId"
                  :label="item.dictName"
                  :value="item.dictTypeId">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 数据标签 -->
            <el-form-item label="数据标签" prop="dictLabel">
              <el-input v-model="formData.dictLabel" placeholder="请输入数据标签" clearable></el-input>
            </el-form-item>
            <!-- 数据键值 -->
            <el-form-item label="数据键值" prop="dictValue">
              <el-input v-model="formData.dictValue" placeholder="请输入数据键值" clearable></el-input>
            </el-form-item>
            <!-- 样式属性 -->
            <el-form-item label="样式属性" prop="cssClass">
              <el-input v-model="formData.cssClass" placeholder="请输入样式属性" clearable></el-input>
            </el-form-item>
            <!-- 字典排序 -->
            <el-form-item label="字典排序" prop="sort">
              <el-input-number v-model="formData.sort" controls-position="right" :min="0" />
            </el-form-item>
            <!-- 回显样式 -->
            <el-form-item label="回显样式" prop="listClass">
              <el-select v-model="formData.listClass" placeholder="请输入回显样式" clearable>
                <el-option v-for="item in listClassOptions" :key="item.value" :label="item.label" :value="item.value">
                  <div class="list-class">
                    <span>{{ item.label }}</span>
                    <el-tag :type="item.value" size="small">{{ item.value }}</el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 状态 -->
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="true">正常</el-radio>
                <el-radio :label="false">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="danger" :loading="buttonLoading" @click="handleClose()" size="small" icon="el-icon-error"> 取消</el-button>
        <el-button type="success" :loading="buttonLoading" @click="submitForm()" size="small" icon="el-icon-success"> 保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '../../../../../components/Pagination/index'
import RightToolbar from '../../../../../components/RightToolbar/index'
import { listDictData, saveDictData, getDictDataById, deleteDictData } from '../../../../../api/system/dict-data'
import { listOption } from '../../../../../api/system/dict-type'

export default {
  name: 'DictData',

  dicts: ['sys_active_state'],

  components: { Pagination, RightToolbar },

  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 是否展示搜索内容
      showSearch: true,
      // 数据总条数
      total: 0,
      // 字典数据对话框是否显示
      dictDataVisible: false,
      // 数据表格等待框
      loading: false,
      // 查询参数
      queryParams: {
        // 页数
        currentPage: 1,
        // 页面大小
        pageSize: 10,
        // 数据标签
        dictLabel: undefined,
        // 字典类型
        dictTypeId: undefined,
        // 状态
        status: undefined,
        // 时间范围
        dataRange: []
      },
      // 字典数据表单对象
      formData: {
        // 字典数据ID
        id: undefined,
        // 样式属性
        cssClass: undefined,
        // 数据标签
        dictLabel: undefined,
        // 字典类型
        dictTypeId: undefined,
        // 数据键值
        dictValue: undefined,
        // 回显样式
        listClass: 'default',
        // 备注
        remark: undefined,
        // 字典排序
        sort: 0,
        // 状态
        status: true
      },
      // 字典数据表单校验规则
      rules: {
        // 数据标签
        dictLabel: [{ required: true, message: '请输入数据标签', trigger: 'blur' }],
        // 数据键值
        dictValue: [{ required: true, message: '请输入数据键值', trigger: 'blur' }],
        // 状态
        status: [{ required: true, message: '请输入状态', trigger: 'blur' }]
      },
      // 字典数据对话框等待框
      dictDataLoading: false,
      // 对话框按钮等待框
      buttonLoading: false,
      // 列信息
      columns: [
        { key: 0, label: '字典排序', visible: true },
        { key: 1, label: '数据标签', visible: true },
        { key: 2, label: '数据键值', visible: true },
        { key: 3, label: '状态', visible: true },
        { key: 4, label: '备注', visible: true },
        { key: 5, label: '创建时间', visible: true }
      ],
      // 表格数据
      tableData: [],
      // 表头选中的数据
      ids: [],
      // 多数据禁用
      single: true,
      // 单数据禁用
      multiple: true,
      // 对话框标题
      dictDataTitle: '',
      // 字典类型选项
      dictTypeOptions: [],
      // 数据标签回显样式
      listClassOptions: [
        {
          value: 'default',
          label: '默认'
        },
        {
          value: 'primary',
          label: '主要'
        },
        {
          value: 'success',
          label: '成功'
        },
        {
          value: 'info',
          label: '信息'
        },
        {
          value: 'warning',
          label: '警告'
        },
        {
          value: 'danger',
          label: '危险'
        }
      ]
    }
  },

  mounted () {
    // 获取到当前路径中的字典类型
    const dictTypeId = this.$route.params.dictTypeId
    // 如果存在字典类型则赋值
    if (dictTypeId) {
      this.queryParams.dictTypeId = dictTypeId
    }
    // 获取字典类型数据
    this.getDictTypeOption()
    // 查询表格数据
    this.getTableData()
  },

  methods: {
    // 获取表格数据
    getTableData () {
      // 开启加载框
      this.loading = true
      listDictData(this.queryParams).then((res) => {
        // 赋值数据参数
        this.tableData = res.list
        this.total = res.total
        // 关闭等待框
        this.loading = false
      }).catch(() => {
        // 确保加载框可以关闭
        this.loading = false
      })
    },
    // 获取字典类型数据
    getDictTypeOption () {
      const that = this
      listOption().then((res) => {
        that.dictTypeOptions = res
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 点击查询按钮
    handleQuery () {
      this.queryParams.currentPage = 1
      this.getTableData()
    },
    // 点击重置按钮
    handleReset () {
      // 数据标签
      this.queryParams.dictLabel = ''
      // 状态
      this.queryParams.status = ''
      this.queryParams.dataRange = []
    },
    // 打开字典数据信息对话框
    handleOpen () {
      // 清除表单数据
      this.reset()
      this.dictDataVisible = true
    },
    // 关闭字典数据对话框表单
    handleClose () {
      this.reset()
      this.dictDataVisible = false
    },
    // 点击新增按钮
    handleAdd () {
      this.dictDataTitle = '新增字典数据'
      this.handleOpen()
    },
    // 点击编辑按钮
    handleUpdate (row) {
      // 修改对话框标题
      this.dictDataTitle = '更新字典数据'
      // 获取到传来的ID
      const dictDataId = row.id || this.ids
      // 打开加载框
      this.dictDataLoading = true
      // 打开编辑字典数据对话框
      this.dictDataVisible = true
      // 根据字典数据ID获取对应的数据
      getDictDataById(dictDataId).then((res) => {
        // 赋值当前的字典数据数据
        this.formData = res
        // 关闭加载框
        this.dictDataLoading = false
      }).catch(() => {
        // 关闭加载框
        this.dictDataLoading = false
      })
    },
    // 点击删除事件
    handleDelete (row) {
      const that = this
      let dictDataIds = []
      if (row.id) {
        dictDataIds.push(row.id)
      } else {
        dictDataIds = this.ids
      }
      this.$confirm('是否确认删除选中的字典数据数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.buttonLoading = true
        that.loading = true
        deleteDictData(dictDataIds).then((res) => {
          that.buttonLoading = false
          that.$message.success('删除成功')
          // 刷新数据
          that.getTableData()
        }).catch(() => {
          // 确保加载框会关闭
          that.buttonLoading = false
          that.loading = false
        })
      }).catch(() => {})
    },
    // 提交表单
    submitForm () {
      const that = this
      this.$refs.dictDataForm.validate(valid => {
        // 校验未通过则直接返回
        if (!valid) return
        // 开启加载框
        that.buttonLoading = true
        that.dictDataLoading = true
        // 提交表单
        saveDictData(that.formData).then((res) => {
          // 根据是否存在ID输出对应消息
          if (that.formData.id) {
            // 输出更新成功信息
            that.$message.success('字典数据信息更新成功')
          } else {
            // 输出添加成功消息
            that.$message.success('字典数据添加成功')
          }
          // 刷新表单数据并关闭对话框
          that.handleClose()
          // 刷新字典数据数据
          that.getTableData()
          // 关闭加载框
          that.buttonLoading = false
          that.dictDataLoading = false
        }).catch(() => {
          // 关闭加载框
          that.buttonLoading = false
          that.dictDataLoading = false
        })
      })
    },
    // 重置表单
    reset () {
      // 清除校验条件
      this.formData = {
        // 字典数据ID
        id: undefined,
        // 数据标签
        dictLabel: undefined,
        // 字典类型
        dictTypeId: this.queryParams.dictTypeId,
        // 数据键值
        dictValue: undefined,
        // 样式属性
        cssClass: undefined,
        // 回显样式
        listClass: 'default',
        // 备注
        remark: undefined,
        // 字典排序
        sort: 0,
        // 状态
        status: true
      }
      // 清除表单校验
      this.resetForm('dictDataForm')
    },
    // 多选框
    handleSelectionChange (selection) {
      // 获取当前选中数组的ID
      this.ids = selection.map(item => item.id)
      // 表头的编辑是否可以点击
      this.single = selection.length !== 1
      // 表头的删除是否可以点击
      this.multiple = !selection.length
    },
    // 取消编辑方法
    close () {
      // 关闭当前标签页
      this.closeCurTags()
      // 跳转到字典管理页面
      this.$router.push('/system/dict-type')
    },
    // 关闭当前标签页方法
    closeCurTags () {
      // 获取当前路径
      const path = this.$route.fullPath
      // 获取当前标签页
      const tagsViewList = this.$store.getters.tagsViewList
      // 默认发布文章是最后一个标签页
      var index = tagsViewList.length - 1
      // 先获取到当前标签页的索引
      for (var i = 0; i < tagsViewList.length; i++) {
        const item = tagsViewList[i]
        // 遍历当前标签页数组
        if (item.fullPath === path) {
          // 找到当前页面对应索引并返回
          index = i
        }
      }
      // 关闭当前标签页
      this.$store.commit('app/REMOVE_TAGS_VIEW', {
        type: 'index',
        index
      })
    }
  }
}

</script>

<style lang="scss" scoped>
.dictData-wrapper {
  padding: 10px 30px;
}
.list-class {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
